package com.registration.service;

import com.registration.bean.ScheduleBean;
import com.registration.mapper.ScheduleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleMapper scheduleMapper;

    @Override
    public List<ScheduleBean> getFutureSchedulesByDoctorId(Integer doctorId) {
        if (doctorId == null) {
            return Collections.emptyList();
        }
        return scheduleMapper.selectSchedulesByDoctorId(doctorId);
    }

    @Override
    /**
     * 检查并锁定号源（不减少剩余号源，加锁防止并发问题）
     */
    @Transactional
    public ScheduleBean checkAndLockQuota(Integer scheduleId) {
        // 1. 加行锁查询，防止并发修改
        ScheduleBean schedule = scheduleMapper.selectScheduleForUpdate(scheduleId);
        if (schedule == null) {
            return null;
        }

        // 2. 检查剩余号源是否充足
        if (schedule.getRemaining_quota() <= 0) {
            throw new RuntimeException("号源已用完");
        }

        // 3. 剩余号源减1（关键：确保每次挂号后序号递增）  updateRemainingQuota
//        schedule.setRemaining_quota(schedule.getRemaining_quota() - 1);
//        scheduleMapper.updateRemainingQuota(schedule.getSchedule_id(), schedule.getRemaining_quota());

        return schedule;
    }




    @Override
    public int decreaseQuota(Integer scheduleId) {
        if (scheduleId == null) {
            return 0;
        }
        return scheduleMapper.decreaseQuota(scheduleId);
    }

    @Override
    public void increaseQuota(Integer scheduleId) {
        if (scheduleId != null) {
            scheduleMapper.increaseQuota(scheduleId);
        }
    }
}
